package bank;

import java.util.ArrayList;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class _57Insert {
    public static int[][] insert(int[][] intervals, int[] newInterval) {
        int[][] newIntervals = new int[intervals.length+1][2];
        for (int i = 0;i < intervals.length;i++){
            newIntervals[i] = intervals[i];
        }
        newIntervals[intervals.length] = newInterval;

        Arrays.sort(newIntervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        List<int[]> list = new ArrayList<>();
        for (int i = 0;i < newIntervals.length;i++){
            int L = newIntervals[i][0],R = newIntervals[i][1];
            if (list.isEmpty() || list.get(list.size()-1)[1] < L){
                //  当前区间的左端点比集合中最后一个区间的右端点大 或者集合为空
                list.add(new int[]{L,R});
            }else {
                list.get(list.size()-1)[1] = Math.max(list.get(list.size()-1)[1],R);
            }
        }
        return list.toArray(new int[list.size()][]);
    }
}
